#include "xmltree.h"

XmlTree::XmlTree()
	:root(NULL)
{ 
}

XmlTree::~XmlTree()
{ 
}
 
void XmlTree::del_node(st_xml_node *node)
{
	if (node == NULL) return;
	if (node->child.size() == 0)
	{
		delete node;
		return;
	}

	for (int i = 0; i < node->child.size(); ++i)
	{
		del_node(node->child[i]);
	}
	
	del_node(node);
}

void XmlTree::reset_tree()
{
	del_node(root);
}

void XmlTree::build_tree(st_xml_node *root_node)
{
	if (root != NULL)
		reset_tree();

	root = root_node;
}

void XmlTree::add_childnode_by_name(core::stringw parentname, st_xml_node *childnode)
{  
	if (root == NULL)
	{
		root = childnode;
	}

	st_xml_node *parent_node = find_node_by_name(root, parentname);
	parent_node->child.push_back(childnode);
}

st_xml_node* XmlTree::find_node_by_name(st_xml_node *cur, core::stringw name)
{ 
	if (cur->name.equals_ignore_case(name))
		return cur; 
	 
	for (int i = 0; i < cur->child.size(); ++i)
	{
		if (find_node_by_name(cur->child[i], name) != NULL)
			return cur->child[i];
	}

	return NULL;
}

void XmlTree::save_node(io::IXMLWriter *writer, st_xml_node *cur)
{
	if (cur->value == L"")
	{
		writer->writeElement(cur->name.c_str());
		writer->writeLineBreak();
	}
	else
	{
		if (cur->child.size() == 0)
		{
			writer->writeElement(L"setting", true, L"name",cur->name.c_str(),L"value",cur->value.c_str());
			writer->writeLineBreak(); 
		} 
	}  

	for (int i = 0; i < cur->child.size(); ++i) 
		save_node(writer, cur->child[i]);
	 
	if (cur->value == L"")
	{
		writer->writeClosingTag(cur->name.c_str()); 
		writer->writeLineBreak();
	} 
}

void XmlTree::save_tree(io::IXMLWriter *writer)
{
	writer->writeXMLHeader();
	save_node(writer, root);
}